<template>
  <view>
    <view class="search-box">
      <!-- 搜索框 -->
      <uni-search-bar
        @input="input"
        placeholder="请输入搜索内容"
        :radius="100"
        bgColor="#EEEEEE"
        cancelButton="none"
        focus="auto"
      ></uni-search-bar>
    </view>

    <!-- 搜索建议的列表 -->
    <view class="sugg-list" v-if="searchResults.length !== 0">
      <view
        class="sugg-item"
        v-for="(item, index) in searchResults"
        :key="index"
        @click="gotoDetail(item)"
      >
        <view class="goods-name">{{ item.goods_name }}</view>
        <uni-icons type="forward" size="16"></uni-icons>
      </view>
    </view>

    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <!-- 标题区域 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="clean"></uni-icons>
      </view>
      <!-- 列表区域  -->
      <view class="history-list">
        <uni-tag
          :text="item"
          v-for="(item, index) in histories"
          :key="index"
          type="warning"
          @click="gotoGoodsList(item)"
        ></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 掩饰其的timerId
      timer: null,
      // 搜索关键词
      kw: '',
      // 搜索结果列表
      searchResults: [],
      // 搜索关键词的历史记录数组
      historyList: []
    };
  },
  onLoad() {
    // 页面一挂载从本地读取用户的搜素历史记录
    this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]');
  },
  methods: {
    // 输入事件
    input(e) {
      // 清除 timer 对应的延时器
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.kw = e;
        // 获取搜索建议列表，搜索框的内容不为空才调用下面的方法,有BUG
        // if (this.kw.trim() !== '') {
        //   this.getSearchResults();
        // }
        this.getSearchResults();
      }, 500);
    },
    async getSearchResults() {
      // 判断关键词是否为空
      if (this.kw.trim() === '') {
        this.searchResults = [];
        return;
      }
      let result = await uni.$http.get(
        `/api/public/v1/goods/qsearch?query=${this.kw}`
      );
      if (result.data.meta.status == 200) {
        this.searchResults = result.data.message;
        this.saveSearchHistory();
      } else {
        return uni.$showMsg();
      }
    },
    // 跳转到商品详情页面
    gotoDetail(item) {
      uni.navigateTo({
        url: `/subpkg/goods_detail/goods_detail?goods_id=${item.goods_id}`
      });
    },
    // 保存搜索历史记录
    saveSearchHistory() {
      if (this.historyList.indexOf(this.kw) == -1) {
        this.historyList.push(this.kw);
        // 调用uni.setStorageSync(key,value) 将搜素历史记录持久化储存到本地
        uni.setStorageSync('kw', JSON.stringify(this.historyList));
      }
      // this.historyList.reverse();
      // this.historyList.unshift(this.kw);

      // // 将Array数组转换成set对象
      // const set = new Set(this.historyList)
      // // 调用 Set 对象的 delete放噶，移除对应的元素
      // set.delete(this.kw)
      // // 调用 Set对象的 add方法，向Set 中添加元素
      // set.add(this.kw)
      // // 将 Set 对象转化成Array数组
      // this.historyList = Array.from(set)
    },
    // 清除搜索历史
    clean() {
      this.historyList = [];
      uni.clearStorageSync('kw');
    },
    // 点击搜索历史跳转到商品列表页面
    gotoGoodsList(item) {
      uni.navigateTo({
        url: `/subpkg/goods_list/goods_list?query=${item}`
      });
    }
  },
  computed: {
    histories() {
      return [...this.historyList].reverse();
    }
  }
};
</script>

<style lang="scss">
.search-box {
  background-color: #c00000;
  position: sticky;
  top: 0;
  z-index: 999;
}

.sugg-list {
  padding: 0 5px;
  .sugg-item {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #efefef;
    padding: 13px 0;
    .goods-name {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-wrap: normal;
      font-size: 12px;
    }
  }
}

.history-box {
  padding: 0 5px;
  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 13px;
    height: 40px;
    border-bottom: 1px solid #efefef;
    margin-bottom: 5px;
  }
  .history-list {
    uni-tag {
      margin-right: 10px;
    }
  }
}
</style>
